package main

import (
	"fmt"
	"sync"
	"time"
)

const (
	GameOfBoating = 1
)

var StartTickMap = map[int32]time.Duration{GameOfBoating: time.Second * 10}

var StartTickEverySecondMap = map[int32]time.Duration{GameOfBoating: time.Second * 10}

type TickProject struct {
	ProjectId int32
}

var TimeTickMap sync.Map

func main() {
	gameP := TickProject{ProjectId: 1}
	var wg sync.WaitGroup
	wg.Add(1)
	go gameP.StartTick(&wg)
	//go gameP.StartTickEverySecond(&wg)
	wg.Wait()
}

func (t *TickProject) StartTick(wg *sync.WaitGroup) {
	tickTime, ok := StartTickMap[t.ProjectId]
	go t.StopTick()
	if ok {
		t.DoTimeTick(tickTime)
	} else {
		t.DoTimeTick(time.Second * 30)
	}
	wg.Done()
}

func (t *TickProject) StartTickEverySecond(wg *sync.WaitGroup) {
	tickTime, ok := StartTickEverySecondMap[t.ProjectId]
	go t.StopTick()
	if ok {
		t.DoTimeTickEverySecond(tickTime)
	} else {
		t.DoTimeTickEverySecond(time.Second * 30)
	}
	wg.Done()
}

func (t *TickProject) DoTimeTick(duration time.Duration) {
	timer := time.NewTimer(duration)
	TimeTickMap.Store(t.ProjectId, make(chan struct{}))
	ticker := time.NewTicker(time.Second * 1) //定义一个1秒间隔的定时器
	defer ticker.Stop()
	defer timer.Stop()
	var index = 10
	for {
		stopTick, ok := TimeTickMap.Load(t.ProjectId)
		if !ok {
			return
		}
		select {
		case <-timer.C:
			fmt.Println("Time out!")
			//todo
			TimeTickMap.Delete(t.ProjectId)
			return
		case <-ticker.C:
			index--
			_, ok := TimeTickMap.Load(t.ProjectId)
			fmt.Println(ok, index)
			t.StopTick()
		case cc := <-stopTick.(chan struct{}):
			fmt.Println("stop")
			fmt.Println("", cc)
			TimeTickMap.Delete(t.ProjectId)
			return
		}
	}

}

func (t *TickProject) DoTimeTickEverySecond(duration time.Duration) {
	timer := time.NewTimer(duration)
	ticker := time.NewTicker(time.Second * 1) //定义一个1秒间隔的定时器
	defer ticker.Stop()
	defer timer.Stop()
	i := 1
	for {
		select {
		case <-timer.C: //结束计时
			fmt.Println("Time out!")
			//TODO

			return
		case <-ticker.C: //每秒执行一次
			if i > 5 {
				return
			}
			fmt.Println(i)
			i++
			//TODO

		}
	}
}

func (t *TickProject) StopTick() {
	//for {
	//	time.Sleep(time.Second * 3)
	//	timerTick, ok := TimeTickMap[t.ProjectId]
	//	if ok {
	//		timerTick.Reset(0)
	//		return
	//	}
	//}
	//time.Sleep(time.Second * 3)
	stopTick, ok := TimeTickMap.Load(t.ProjectId)
	if ok {
		stopTick.(chan struct{}) <- struct{}{}
	}

}
